package com.zp.resource;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.springframework.stereotype.Component;

import com.sun.jersey.spi.resource.Singleton;
import com.zp.bean.common.ResultCommonVo;
import com.zp.bean.paper.AnswerItemVo;
import com.zp.bean.paper.QuestionVo;
import com.zp.bean.paper.ResultAnswerItemVo;
import com.zp.bean.paper.ResultQuestionVo;
import com.zp.domain.AnswerItem;
import com.zp.domain.Question;
import com.zp.resource.common.BaseServices;
import com.zp.util.Constant;
import com.zp.util.MyException;

/**
 * question services
 * 
 * @author chenlijun08@gmail.com
 * 
 * @version 1.0
 * 
 * @date 2014/2/22
 * 
 */
@Component
@Path("/rest/question")
@Singleton
public class QuestionServices extends BaseServices {

	/**
	 * add one Question path:/question/addQuestion Http:POST
	 * 
	 * @param question
	 * 
	 * @return Response, ResultCommonVo with JSON String
	 *         like:{"code":268,"message":"OK","totalCount":0}
	 */
	@POST
	@Path("/addQuestion")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response addQuestion(Question question) {
		ResultCommonVo result = new ResultCommonVo();
		try {
			jpaDao.save(question);
			result.setCode(Constant.SUCCESS_CODE);
			result.setMessage(Constant.OK);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return Response.ok(result).build();
	}

	/**
	 * update one Question path:/question/updateQuestion Http:PUT
	 * 
	 * @param question
	 * 
	 * @return Response, ResultQuestionVo with JSON String
	 *         like:{"code":268,"message":"OK","totalCount":0,"vo":{"id":
	 *         "402881e6445cc3a301445cc4332b0001"
	 *         ,"title":"心理关爱题目11","questionType"
	 *         :{"id":"402881e6445c8fc601445c980f1f0005"
	 *         ,"name":"单选题","code":"QUS00001"
	 *         ,"parentCode":"QU0001"},"businessType"
	 *         :null,"item":null},"list":null}
	 */
	@PUT
	@Path("/updateQuestion")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response updateQuestion(Question question) {
		ResultQuestionVo result = new ResultQuestionVo();
		try {
			jpaDao.update(question);
			QuestionVo vo = new QuestionVo();
			vo.setBusinessType(null);
			vo.setId(question.getId());
			try {
				vo.setItem((AnswerItem) this.jpaDao.findById(AnswerItem.class,
						question.getQuestionAnswer()));
			} catch (IllegalArgumentException e) {
				vo.setItem(null);
			}
			vo.setQuestionType(this.getTypeByCode(question.getQuestionType()));
			vo.setTitle(question.getTitle());
			result.setVo(vo);
			result.setCode(Constant.SUCCESS_CODE);
			result.setMessage(Constant.OK);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return Response.ok(result).build();
	}

	/**
	 * delete Question by id path:/question/deleteQuestion Http:DELETE
	 * 
	 * @param questionId
	 *            primary key of Question
	 * 
	 * @return Response, ResultCommonVo with JSON String
	 *         like:{"code":268,"message":"OK","totalCount":1}
	 */
	@DELETE
	@Path("/deleteQuestion")
	@Produces(MediaType.APPLICATION_JSON)
	public Response deleteQuestion(@QueryParam("questionId") String questionId) {
		logger.info("deleteQuestion called questionId:" + questionId);
		ResultCommonVo result = new ResultCommonVo();
		try {
			jpaDao.deleteById(Question.class, questionId);
			result.setCode(Constant.SUCCESS_CODE);
			result.setMessage(Constant.OK);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return Response.ok(result).build();
	}

	/**
	 * get Question by id path:/question/getQuestion Http:GET
	 * 
	 * @param questionId
	 *            primary key of Question
	 * 
	 * @return Response, ResultQuestionVo with JSON String
	 *         like:{"code":268,"message":"OK","totalCount":0,"vo":{"id":
	 *         "402881e6445cc3a301445cc4332b0001"
	 *         ,"title":"心理关爱题目11","questionType"
	 *         :{"id":"402881e6445c8fc601445c980f1f0005"
	 *         ,"name":"单选题","code":"QUS00001"
	 *         ,"parentCode":"QU0001"},"businessType"
	 *         :null,"item":null},"list":null}
	 * 
	 */
	@GET
	@Path("/getQuestion")
	@Produces(MediaType.APPLICATION_JSON)
	public Response getQuestionById(@QueryParam("questionId") String questionId) {
		logger.info("getQuestionById called questionId:" + questionId);
		ResultQuestionVo result = new ResultQuestionVo();
		try {
			Question question = (Question) jpaDao.findById(Question.class,
					questionId);
			QuestionVo vo = new QuestionVo();
			vo.setBusinessType(null);
			vo.setId(question.getId());
			vo.setItem((AnswerItem) this.jpaDao.findById(AnswerItem.class,
					question.getQuestionAnswer()));
			vo.setQuestionType(this.getTypeByCode(question.getQuestionType()));
			vo.setTitle(question.getTitle());
			result.setVo(vo);
			result.setCode(Constant.SUCCESS_CODE);
			result.setMessage(Constant.OK);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return Response.ok(result).build();
	}

	/**
	 * get all the answer items with question id
	 * 
	 * @param questionId
	 * @return Response,ResultAnswerItemVo with JSON String
	 *         like:{"code":268,"message"
	 *         :"OK","totalCount":4,"vo":null,"list":[{
	 *         "id":"402881e6445d4c3701445d515f8e0002"
	 *         ,"code":"A","question":null
	 *         ,"value":"心理关爱题目1答案1"},{"id":"402881e6445d53b401445d54be830001"
	 *         ,"code":"B","question":null,"value":"心理关爱题目1答案2"},{"id":
	 *         "402881e6445d53b401445d54fa180002"
	 *         ,"code":"C","question":null,"value"
	 *         :"心理关爱题目1答案3"},{"id":"402881e6445d53b401445d55bb6b0003"
	 *         ,"code":"D","question":null,"value":"心理关爱题目1答案4"}]}
	 */
	@GET
	@Path("/getAitems")
	@Produces(MediaType.APPLICATION_JSON)
	public Response getAnswerItemFromQuestion(
			@QueryParam("questionId") String questionId) {
		logger.info("getAnswerItemFromQuestion called questionId:" + questionId);
		ResultAnswerItemVo result = new ResultAnswerItemVo();
		String jpql = "from AnswerItem where questionId=?";
		String countSql = "select count(id) from AnswerItem where questionId=?";
		List<?> list = null;
		List<AnswerItemVo> lt = new ArrayList<AnswerItemVo>();
		result.setCode(Constant.SUCCESS_CODE);
		result.setMessage(Constant.OK);

		Object[] param = { questionId };
		try {
			list = this.jpaDao.getResultData(Constant.NEGATIVE_ONE,
					Constant.NEGATIVE_ONE, jpql, param);
			long totalCount = this.jpaDao.getCount(countSql, param);
			result.setTotalCount(totalCount);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();

		}
		if (list != null && list.size() > Constant.ZERO) {
			for (Object o : list) {
				AnswerItem aitem = (AnswerItem) o;
				AnswerItemVo vo = new AnswerItemVo();
				vo.setId(aitem.getId());
				vo.setCode(aitem.getAnswerCode());
				vo.setQuestion(null);
				vo.setValue(aitem.getValue());
				lt.add(vo);
			}
			result.setList(lt);

		}
		return Response.ok(result).build();
	}

	/**
	 * 
	 * get question with page parameters and search condition
	 * path:/question/getQuestions Http:GET
	 * 
	 * @param pageNo
	 * 
	 * @param pageSize
	 * 
	 * @param questionTitle
	 *            the title of question if ignored the value is null
	 * 
	 * @return Response, ResultQuestionVo with JSON String
	 *         like:{"code":268,"message"
	 *         :"OK","totalCount":10,"vo":null,"list":[
	 *         {"id":"402881e6445cc3a301445cc4332b0001"
	 *         ,"title":"心理关爱题目1","questionType"
	 *         :{"id":"402881e6445c8fc601445c980f1f0005"
	 *         ,"name":"单选题","code":"QUS00001"
	 *         ,"parentCode":"QU0001"},"businessType"
	 *         :null,"item":null},{"id":"402881e6445cc3a301445cc62ac7000a"
	 *         ,"title":"心理关爱题目10","questionType":{"id":
	 *         "402881e6445c8fc601445c980f1f0005"
	 *         ,"name":"单选题","code":"QUS00001",
	 *         "parentCode":"QU0001"},"businessType":null,"item":null}]}
	 * 
	 * 
	 */
	@GET
	@Path("/getQuestions")
	@Produces({ MediaType.APPLICATION_JSON })
	public Response getQuestionByCodeName(@QueryParam("pageNo") int pageNo,
			@QueryParam("pageSize") int pageSize,
			@QueryParam("questionTitle") String questionTitle) {
		logger.info("getQuestionByCodeName called json pageNo:" + pageNo
				+ " pageSize:" + pageSize + " questionTitle:" + questionTitle);
		String jpql = "from Question where title=? order by title asc";
		String countSql = "select count(id) from Question where title=? order by title asc";
		List<?> list = null;
		ResultQuestionVo result = new ResultQuestionVo();
		List<QuestionVo> lt = new ArrayList<QuestionVo>();
		result.setCode(Constant.SUCCESS_CODE);
		result.setMessage(Constant.OK);
		if ("".equals(questionTitle) || questionTitle == null) {
			jpql = "from Question order by title asc";
			countSql = "select count(id) from Question order by title asc";
			try {
				list = this.jpaDao.getResultData(pageNo, pageSize, jpql, null);
				long totalCount = this.jpaDao.getCount(countSql, null);
				result.setTotalCount(totalCount);
			} catch (MyException e) {
				result.setCode(Constant.FAILE_CODE);
				result.setMessage(e.getMessage());
				e.printStackTrace();
			}
		} else {
			Object[] param = { questionTitle };
			try {
				list = this.jpaDao.getResultData(pageNo, pageSize, jpql, param);
				long totalCount = this.jpaDao.getCount(countSql, param);
				result.setTotalCount(totalCount);
			} catch (MyException e) {
				result.setCode(Constant.FAILE_CODE);
				result.setMessage(e.getMessage());
				e.printStackTrace();
			}
		}
		if (list != null && list.size() > Constant.ZERO) {
			for (Object o : list) {
				Question question = (Question) o;
				QuestionVo vo = new QuestionVo();
				vo.setBusinessType(null);
				vo.setId(question.getId());
				try {
					vo.setItem((AnswerItem) this.jpaDao.findById(
							AnswerItem.class, question.getQuestionAnswer()));

				} catch (MyException e) {
					vo.setItem(null);
				}
				vo.setQuestionType(this.getTypeByCode(question
						.getQuestionType()));
				vo.setTitle(question.getTitle());
				lt.add(vo);

			}
			result.setList(lt);

		}
		return Response.ok(result).build();
	}
}
